<template>
  <!-- 配件销售出库 -->
  <div>
    <TopFilter ref="topFilter" labelWidth="110" :list="topFilterList" @filterChange="handleSearch"></TopFilter>

    <FilterTable
      ref="table"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :columns="columns"
      :datakey="'rows'"
      columnsRef="part_partOutbound_partSalesOutbound"
      selectionType="single"
      :onRowSelectChange="handleTableRowSelectChange"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls">
        <AjaxButton size="small" type="primary" :click="handleOutbound">执行出库</AjaxButton>
      </template>
    </FilterTable>

    <!-- 配件销售订单详情 -->
    <BaseDialog title="配件销售单详情" :visible.sync="orderDetailVisible" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <orderDetail :partSaleNo="checkedSaleOrderNo" @close="orderDetailVisible = false" />
    </BaseDialog>

    <!-- 出库单打印数据 -->
    <BasePrint ref="Salesprint" :data="printList" template="templateSales" />
  </div>
</template>

<script>
import { searchSalesPart, printData } from '@/api/part/partOut/partSales/index';
import { getAllUser, querySysParam } from '@/api/part/common';
import { executeOutbound } from '@/api/part/partOutbound/partSaalesOutBound';
import { queryCompanyInforById } from '@/api/repair/repairReception/feesSettlement';

import { dictionary } from '@/utils/dictMixin';
import { notifyAction, setRound } from '@/utils';
import { getUser, getCompanyId } from '@/assets/js/auth';

import orderDetail from './orderDetail';
import { dealerPrintApi } from '@/api/repair/index.js';

export default {
  components: {
    orderDetail
  },
  mixins: [dictionary],
  data() {
    return {
      fetchapi: searchSalesPart,
      fetchParams: {
        xhrAbort: false,
        isFinish: 10041002,
        balanceStatus: 10041001
      },
      columns: this.createTableColumns(),
      topFilterList: this.createTopFilterList(),
      selectTableList: [], // 选中的table行项
      orderDetailVisible: false, // 是否显示table详情
      checkedSaleOrderNo: '', // 查看详情的配件销售单号
      printList: [], // 打印数据
      cunUserList: [], // 人员数据列表
      printParams: {} // 打印参数
    };
  },
  mounted() {
    this.getAllUser();
    this.queryPrintSysParam();
    this.queryPrintParams();
  },
  methods: {
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'cIndex',
          sorter: true,
          width: 70,
          render: params => {
            return <span>{params.row.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 90,
          render: params => {
            return (
              <div>
                <el-button
                  type="text"
                  onClick={() => {
                    this.handleViewDetail(params.row);
                  }}
                >
                  详情
                </el-button>
              </div>
            );
          }
        },
        {
          title: '配件销售单号',
          dataIndex: 'SALES_PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '开单日期',
          dataIndex: 'CREATED_AT',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '结算日期',
          dataIndex: 'BALANCE_TIME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '客户代码',
          dataIndex: 'CUSTOMER_CODE',
          width: 120,
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'CUSTOMER_NAME',
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '销售材料费',
          dataIndex: 'SALES_PART_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'number',
          showOverflowTooltip: true
        },
        // {
        //   title: '结算状态',
        //   dataIndex: 'BALANCE_STATUS',
        //   sorter: true,
        //   showOverflowTooltip: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1004'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.BALANCE_STATUS, '1004')}</span>;
        //   }
        // },
        {
          title: '制单人',
          dataIndex: 'CREATED_BY',
          dictItems: [],
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          showOverflowTooltip: true
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '配件销售单号',
          fieldName: 'salesNo'
        },
        {
          type: 'RANGE_DATE',
          fieldName: 'dateBegin|dateEnd',
          labelOptions: {
            type: 'SELECT',
            fieldName: 'dateType',
            itemList: [
              { text: '开单日期', value: 'createdAt' },
              { text: '结算日期', value: 'balanceTime' }
            ]
          }
        },
        {
          type: 'CHECKBOX',
          label: '打印单据',
          fieldName: 'autoPrint',
          options: {
            trueValue: '0',
            falseValue: '1'
          },
          initialValue: '1'
        }
      ];
    },
    // 点击搜索
    handleSearch(val) {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign(this.fetchParams, val, {
        xhrAbort: false
      });
    },
    // table列选中
    handleTableRowSelectChange(e) {
      this.selectTableList = e;
    },
    // 查询所有员工
    async getAllUser() {
      let res = await getAllUser();
      if (res.resultCode == 200) {
        let userList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
        this.columns.find(item => item.dataIndex == 'CREATED_BY').dictItems = userList;
        this.columns.find(item => item.dataIndex == 'CREATED_BY').filterItems = userList;
        this.cunUserList = userList;
      }
    },
    // 点击执行出库
    async handleOutbound() {
      let res = {};
      if (!this.selectTableList.length) {
        return notifyAction('请选择需要出库的订单', 'warning');
      } else {
        let salesPartNo = this.selectTableList[0].SALES_PART_NO;
        if (this.selectTableList[0].SALES_PART_AMOUNT == 0) {
          let status = await this.$confirm('销售材料费为0是否确认出库?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });
          if (status !== 'confirm') {
            return;
          }
        }
        res = await executeOutbound({
          billNo: salesPartNo
        });
        if (res.resultCode == 200) {
          notifyAction('出库成功', 'success');
          this.fetchParams.xhrAbort = true;
          this.fetchParams.xhrAbort = false;
          // 勾选打印的话直接调取打印方法
          let defaultPrint = this.topFilterList.find(item => item.fieldName == 'autoPrint').initialValue;
          if (defaultPrint == '0') {
            this.getPrintData(salesPartNo);
          }
        }
      }
    },
    // 点击查看详情
    handleViewDetail(row) {
      // console.log(row, '点击查看详情');
      this.checkedSaleOrderNo = row.SALES_PART_NO;
      this.orderDetailVisible = true;
    },
    // 获取打印默认参数
    async queryPrintSysParam() {
      let res = await querySysParam('spa', 'DYCKD');
      console.log(res, '打印出库单默认参数');
      if (res.resultCode == 200 && res.data.length) {
        this.topFilterList.find(item => item.fieldName == 'autoPrint').initialValue = res.data[0].bParaValue;
      }
    },
    // 获取打印数据（出库单）
    async getPrintData(salesPartNo) {
      const res = await printData(salesPartNo); // 获取当前行数据
      this.printList = res.data;
      // 获取公司信息
      let compInfo = {};
      try {
        let compres = await queryCompanyInforById({
          owenrCode: getCompanyId()
        });
        if (compres.resultCode == 200) {
          this.printList.compInfo = compres.data;
        }
      } catch (err) {
        console.log(err, '获取公司信息失败');
      }
      // 手动翻译部分数据
      try {
        this.printList.baseInfo.USER_NAME = this.cunUserList.find(item => item.value == this.printList.baseInfo.USER_ID).text || '';
      } catch (err) {
        console.log(err, '翻译部分数据失败');
      }
      if (this.printList.baseInfo.SALES_PART_AMOUNT) {
        this.printList.baseInfo.SALES_PART_AMOUNT = setRound(this.printList.baseInfo.SALES_PART_AMOUNT);
      }
      this.$refs.print.EXCUTE_PRINT();
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJCK'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
        this.printParams.vDirectPrint = this.printParams.vDirectPrint === 0 ? '0' : this.printParams.vDirectPrin;
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>
